import React from 'react'

import './css/Tabs.css'

/* 页签 */
class Tabs extends React.Component {
    constructor(props) {
        super(props)
        this.state = {
            width: document.documentElement.clientWidth || document.body.clientWidth,
            currentSelect: 0,
        }
    }

    componentWillMount = () => {
        if(this.props.currentSelect){
            this.setState({
                currentSelect: this.props.currentSelect
            });
        }
    }

    componentDidMount = () => {
        window.onresize = () => {
            this.setState({
                width: document.documentElement.clientWidth || document.body.clientWidth
            })
        }
    }

    tabClick = (item, index) => {
        if(this.props.onClick){
            this.props.onClick(item, index);
        }
        this.setState({
            currentSelect: index
        });
    }

    setSelect = (currentSelect) => {
        this.setState({currentSelect});
    }

    render() {
        const {dataSource,config} = this.props;
        let {width,currentSelect} = this.state;
        const {tabClick} = this;

        switch(dataSource.length){
            case 2:
                width = width - 4;
            break;

            case 3:
                width = width - 6;
            break;
        }

        let tabs = [];
        if(config.type == 'card'){
            tabs.push(
                dataSource.map((item,i)=>{
                    return (
                        <div className='card-container'>
                            <div className={currentSelect==i?'card-select':'card'} style={{width:config.itemWidth||90}} onClick={()=>tabClick(item,i)}>{item.text}</div>
                        </div>
                    )
                })
            );
        }else{
            if(!config.color){
                config.color = '#FFF';
            }
            tabs.push(
                dataSource.map((item,i)=>{
                    return (
                        <div className='container'>
                            <div className={currentSelect==i?'item-select':'item'} style={{width:width/dataSource.length}} onClick={()=>tabClick(item,i)}>{item.text}</div>
                            <div className='triangle' style={{borderColor:`transparent transparent ${config.color} transparent`,left:width/dataSource.length/2+i*(width/dataSource.length)-10,display:currentSelect==i?'':'none'}}></div>
                        </div>
                    )
                })
            )
        }

        return (
            <div className='Tabs' style={{height:config.height?config.height+'px':'47px'}}>
                {tabs}
            </div>
        )
    }
}

export default Tabs
